<!DOCTYPE html>
<html lang=en>
<head>
    <!-- so meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="HandheldFriendly" content="True">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="description" content="pom.xml添加依赖12345678&amp;lt;dependency&amp;gt;    &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;&#x2F;groupId&amp;gt;    &amp;lt;artifactId&amp;gt;spring-boot-starter-data-redis&amp;lt;&#x2F;artifactId&amp;gt;&amp;lt;&#x2F;dependency&amp;gt;&amp;lt;dependenc">
<meta name="keywords" content="Java,笔记,SpringBoot,Redis">
<meta property="og:type" content="article">
<meta property="og:title" content="Springboot整合redis">
<meta property="og:url" content="http:&#x2F;&#x2F;yoursite.com&#x2F;2019&#x2F;10&#x2F;17&#x2F;Springboot%E6%95%B4%E5%90%88redis&#x2F;index.html">
<meta property="og:site_name" content="ECIN&#39;S BLOG">
<meta property="og:description" content="pom.xml添加依赖12345678&amp;lt;dependency&amp;gt;    &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;&#x2F;groupId&amp;gt;    &amp;lt;artifactId&amp;gt;spring-boot-starter-data-redis&amp;lt;&#x2F;artifactId&amp;gt;&amp;lt;&#x2F;dependency&amp;gt;&amp;lt;dependenc">
<meta property="og:locale" content="en">
<meta property="og:image" content="http:&#x2F;&#x2F;106.15.200.82&#x2F;source&#x2F;1571211982004.jpg">
<meta property="og:image" content="http:&#x2F;&#x2F;106.15.200.82&#x2F;source&#x2F;1571211081508.jpg">
<meta property="og:image" content="http:&#x2F;&#x2F;106.15.200.82&#x2F;source&#x2F;1572835256334.jpg">
<meta property="og:updated_time" content="2020-01-30T02:16:01.069Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http:&#x2F;&#x2F;106.15.200.82&#x2F;source&#x2F;1571211982004.jpg">
    
    
        
          
              <link rel="shortcut icon" href="/images/favicon.ico">
          
        
        
          
            <link rel="icon" type="image/png" href="/images/favicon-192x192.png" sizes="192x192">
          
        
        
          
            <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png">
          
        
    
    <!-- title -->
    <title>Springboot整合redis</title>
    <!-- styles -->
    <link rel="stylesheet" href="/css/style.css">
    <!-- persian styles -->
    
      <link rel="stylesheet" href="/css/rtl.css">
    
    <!-- rss -->
    
    
</head>

<body class="max-width mx-auto px3 ltr">
    
      <div id="header-post">
  <a id="menu-icon" href="#"><i class="fas fa-bars fa-lg"></i></a>
  <a id="menu-icon-tablet" href="#"><i class="fas fa-bars fa-lg"></i></a>
  <a id="top-icon-tablet" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');" style="display:none;"><i class="fas fa-chevron-up fa-lg"></i></a>
  <span id="menu">
    <span id="nav">
      <ul>
         
          <li><a href="/">Home</a></li>
         
          <li><a href="/about/">About</a></li>
         
          <li><a href="/archives/">Writing</a></li>
         
          <li><a href="/projects_url">Projects</a></li>
        
      </ul>
    </span>
    <br/>
    <span id="actions">
      <ul>
        
        <li><a class="icon" href="/2019/10/18/BTSow%20Spider/"><i class="fas fa-chevron-left" aria-hidden="true" onmouseover="$('#i-prev').toggle();" onmouseout="$('#i-prev').toggle();"></i></a></li>
        
        
        <li><a class="icon" href="/2019/10/17/ES6%E8%AF%AD%E6%B3%95%E7%AC%94%E8%AE%B0/"><i class="fas fa-chevron-right" aria-hidden="true" onmouseover="$('#i-next').toggle();" onmouseout="$('#i-next').toggle();"></i></a></li>
        
        <li><a class="icon" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up" aria-hidden="true" onmouseover="$('#i-top').toggle();" onmouseout="$('#i-top').toggle();"></i></a></li>
        <li><a class="icon" href="#"><i class="fas fa-share-alt" aria-hidden="true" onmouseover="$('#i-share').toggle();" onmouseout="$('#i-share').toggle();" onclick="$('#share').toggle();return false;"></i></a></li>
      </ul>
      <span id="i-prev" class="info" style="display:none;">Previous post</span>
      <span id="i-next" class="info" style="display:none;">Next post</span>
      <span id="i-top" class="info" style="display:none;">Back to top</span>
      <span id="i-share" class="info" style="display:none;">Share post</span>
    </span>
    <br/>
    <div id="share" style="display: none">
      <ul>
  <li><a class="icon" href="http://www.facebook.com/sharer.php?u=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/" target="_blank" rel="noopener"><i class="fab fa-facebook " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://twitter.com/share?url=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&text=Springboot整合redis" target="_blank" rel="noopener"><i class="fab fa-twitter " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.linkedin.com/shareArticle?url=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&title=Springboot整合redis" target="_blank" rel="noopener"><i class="fab fa-linkedin " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://pinterest.com/pin/create/bookmarklet/?url=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&is_video=false&description=Springboot整合redis" target="_blank" rel="noopener"><i class="fab fa-pinterest " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=Springboot整合redis&body=Check out this article: http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/" target="_blank" rel="noopener"><i class="fas fa-envelope " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://getpocket.com/save?url=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&title=Springboot整合redis" target="_blank" rel="noopener"><i class="fab fa-get-pocket " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://reddit.com/submit?url=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&title=Springboot整合redis" target="_blank" rel="noopener"><i class="fab fa-reddit " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.stumbleupon.com/submit?url=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&title=Springboot整合redis" target="_blank" rel="noopener"><i class="fab fa-stumbleupon " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://digg.com/submit?url=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&title=Springboot整合redis" target="_blank" rel="noopener"><i class="fab fa-digg " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.tumblr.com/share/link?url=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&name=Springboot整合redis&description=" target="_blank" rel="noopener"><i class="fab fa-tumblr " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://news.ycombinator.com/submitlink?u=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&t=Springboot整合redis" target="_blank" rel="noopener"><i class="fab fa-hacker-news " aria-hidden="true"></i></a></li>
</ul>

    </div>
    <div id="toc">
      <ol class="toc"><li class="toc-item toc-level-4"><a class="toc-link" href="#pom-xml添加依赖"><span class="toc-number">1.</span> <span class="toc-text">pom.xml添加依赖</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#开启缓存注解"><span class="toc-number">2.</span> <span class="toc-text">开启缓存注解</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#添加配置类RedisConfig"><span class="toc-number">3.</span> <span class="toc-text">添加配置类RedisConfig</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#application-yml"><span class="toc-number">4.</span> <span class="toc-text">application.yml</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#使用时需要注入"><span class="toc-number">5.</span> <span class="toc-text">使用时需要注入</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#simple-sample"><span class="toc-number"></span> <span class="toc-text">simple sample</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#缓存普通k-v"><span class="toc-number">0.1.</span> <span class="toc-text">缓存普通k-v</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#设置过期时间"><span class="toc-number">0.2.</span> <span class="toc-text">设置过期时间</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#对象缓存"><span class="toc-number">0.3.</span> <span class="toc-text">对象缓存</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#读取"><span class="toc-number">0.4.</span> <span class="toc-text">读取</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#存取List"><span class="toc-number">0.5.</span> <span class="toc-text">存取List</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#但是在真正的项目中，使用redis整合spring-cache注解会更加方便，开始讲解reids配合spring-cache注解进行开发"><span class="toc-number"></span> <span class="toc-text">但是在真正的项目中，使用redis整合spring cache注解会更加方便，开始讲解reids配合spring cache注解进行开发</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#有一个地方要注意，如果项目使用了shiro，注解将失效，必须在Relm中加入-Lazy注解"><span class="toc-number"></span> <span class="toc-text">有一个地方要注意，如果项目使用了shiro，注解将失效，必须在Relm中加入@Lazy注解</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Cacheable"><span class="toc-number">1.</span> <span class="toc-text">@Cacheable</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#CachePut"><span class="toc-number">2.</span> <span class="toc-text">@CachePut</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#CacheEvict"><span class="toc-number">3.</span> <span class="toc-text">@CacheEvict</span></a></li></ol>
    </div>
  </span>
</div>

    
    <div class="content index py4">
        
        <article class="post" itemscope itemtype="http://schema.org/BlogPosting">
  <header>
    
    <h1 class="posttitle" itemprop="name headline">
        Springboot整合redis
    </h1>



    <div class="meta">
      <span class="author" itemprop="author" itemscope itemtype="http://schema.org/Person">
        <span itemprop="name">ECIN'S BLOG</span>
      </span>
      
    <div class="postdate">
      
        <time datetime="2019-10-17T07:27:32.000Z" itemprop="datePublished">2019-10-17</time>
        
      
    </div>


      

      
    <div class="article-tag">
        <i class="fas fa-tag"></i>
        <a class="tag-link" href="/tags/Java/" rel="tag">Java</a>, <a class="tag-link" href="/tags/Redis/" rel="tag">Redis</a>, <a class="tag-link" href="/tags/SpringBoot/" rel="tag">SpringBoot</a>, <a class="tag-link" href="/tags/%E7%AC%94%E8%AE%B0/" rel="tag">笔记</a>
    </div>


    </div>
  </header>
  

  <div class="content" itemprop="articleBody">
    <p><img src="http://106.15.200.82/source/1571211982004.jpg" alt="image.png"></p>
<h4 id="pom-xml添加依赖"><a href="#pom-xml添加依赖" class="headerlink" title="pom.xml添加依赖"></a>pom.xml添加依赖</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-data-redis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>redis.clients<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jedis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="开启缓存注解"><a href="#开启缓存注解" class="headerlink" title="开启缓存注解"></a>开启缓存注解</h4><p><img src="http://106.15.200.82/source/1571211081508.jpg" alt="image.png"></p>
<h4 id="添加配置类RedisConfig"><a href="#添加配置类RedisConfig" class="headerlink" title="添加配置类RedisConfig"></a>添加配置类RedisConfig</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">@Configuration</span><br><span class="line">public class RedisConfig &#123;</span><br><span class="line"></span><br><span class="line">    @Bean</span><br><span class="line">    @ConditionalOnMissingBean(name = &quot;redisTemplate&quot;)</span><br><span class="line">    public RedisTemplate&lt;String,Object&gt; redisTemplate(RedisConnectionFactory redisConnectionFactory)&#123;</span><br><span class="line">        Jackson2JsonRedisSerializer&lt;Object&gt; jackson2JsonRedisSerializer = </span><br><span class="line">                new Jackson2JsonRedisSerializer&lt;Object&gt;(Object.class);</span><br><span class="line">        ObjectMapper objectMapper = new ObjectMapper();</span><br><span class="line">        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);</span><br><span class="line">        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);</span><br><span class="line">        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);</span><br><span class="line"></span><br><span class="line">        RedisTemplate&lt;String,Object&gt; template = new RedisTemplate&lt;String,Object&gt;();</span><br><span class="line">        template.setConnectionFactory(redisConnectionFactory);</span><br><span class="line">        template.setKeySerializer(jackson2JsonRedisSerializer);</span><br><span class="line">        template.setValueSerializer(jackson2JsonRedisSerializer);</span><br><span class="line">        template.setHashKeySerializer(jackson2JsonRedisSerializer);</span><br><span class="line">        template.setHashValueSerializer(jackson2JsonRedisSerializer);</span><br><span class="line">        template.afterPropertiesSet();</span><br><span class="line">        return template;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Bean</span><br><span class="line">    @ConditionalOnMissingBean(StringRedisTemplate.class)</span><br><span class="line">    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)&#123;</span><br><span class="line">        StringRedisTemplate template = new StringRedisTemplate();</span><br><span class="line">        template.setConnectionFactory(redisConnectionFactory);</span><br><span class="line">        return template;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="application-yml"><a href="#application-yml" class="headerlink" title="application.yml"></a>application.yml</h4><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line"><span class="attr">  redis:</span></span><br><span class="line"><span class="attr">    host:</span> <span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span></span><br><span class="line"><span class="attr">    port:</span> <span class="number">6379</span></span><br><span class="line"><span class="attr">    jedis:</span></span><br><span class="line"><span class="attr">      pool:</span></span><br><span class="line"><span class="attr">        max-active:</span> <span class="number">8</span></span><br><span class="line"><span class="attr">        max-wait:</span> <span class="bullet">-1</span></span><br><span class="line"><span class="attr">        max-idle:</span> <span class="number">500</span></span><br><span class="line"><span class="attr">        min-idle:</span> <span class="number">0</span></span><br><span class="line"><span class="attr">    lettuce:</span></span><br><span class="line"><span class="attr">      shutdown-timeout:</span> <span class="number">0</span></span><br></pre></td></tr></table></figure>
<h4 id="使用时需要注入"><a href="#使用时需要注入" class="headerlink" title="使用时需要注入"></a>使用时需要注入</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="keyword">private</span> StringRedisTemplate stringRedisTemplate;</span><br></pre></td></tr></table></figure>

<h3 id="simple-sample"><a href="#simple-sample" class="headerlink" title="simple sample"></a>simple sample</h3><h5 id="缓存普通k-v"><a href="#缓存普通k-v" class="headerlink" title="缓存普通k-v"></a>缓存普通k-v</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">redisTemplate.opsForValue().set(<span class="string">"name"</span>,<span class="string">"Jenny"</span>);</span><br></pre></td></tr></table></figure>
<p>读取k-v</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">redisTemplate.opsForValue().get(<span class="string">"name"</span>);</span><br></pre></td></tr></table></figure>
<h5 id="设置过期时间"><a href="#设置过期时间" class="headerlink" title="设置过期时间"></a>设置过期时间</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*15s*/</span></span><br><span class="line">redisTemplate.opsForValue().set(<span class="string">"name"</span>, <span class="string">"Jenny"</span>, <span class="number">15</span>, TimeUnit.SECONDS);</span><br></pre></td></tr></table></figure>

<h5 id="对象缓存"><a href="#对象缓存" class="headerlink" title="对象缓存"></a>对象缓存</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">User user = <span class="keyword">new</span> User();</span><br><span class="line">user.setId(<span class="string">"20172670****"</span>);</span><br><span class="line">user.setName(<span class="string">"郭伟"</span>);</span><br><span class="line">user.setTel(<span class="string">"1560794****"</span>);</span><br><span class="line">user.setMoney(<span class="number">500</span>);</span><br><span class="line"></span><br><span class="line">redisTemplate.opsForValue().set(<span class="string">"user"</span>,user);</span><br></pre></td></tr></table></figure>
<h5 id="读取"><a href="#读取" class="headerlink" title="读取"></a>读取</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">User user = (User)redisTemplate.opsForValue().get(<span class="string">"user"</span>);</span><br></pre></td></tr></table></figure>
<h5 id="存取List"><a href="#存取List" class="headerlink" title="存取List"></a>存取List<User></h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">List&lt;User&gt; list = userService.getAllUsers();</span><br><span class="line">redisTemplate.opsForValue().set(<span class="string">"list"</span>,list);</span><br><span class="line"></span><br><span class="line">List&lt;User&gt; list1 = (List&lt;User&gt;) redisTemplate.opsForValue().get(<span class="string">"list"</span>);</span><br><span class="line"><span class="keyword">for</span>(User user1: list1)&#123;</span><br><span class="line">    System.out.println(user1.toString());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当然redis的存储结构不止这些<br>string（字符串），hash（哈希），list（列表），set（集合）及zset(sorted set：有序集合)<br><a href="https://blog.csdn.net/weixin_40461281/article/details/82011670" target="_blank" rel="noopener">参考这里</a></p>
<h3 id="但是在真正的项目中，使用redis整合spring-cache注解会更加方便，开始讲解reids配合spring-cache注解进行开发"><a href="#但是在真正的项目中，使用redis整合spring-cache注解会更加方便，开始讲解reids配合spring-cache注解进行开发" class="headerlink" title="但是在真正的项目中，使用redis整合spring cache注解会更加方便，开始讲解reids配合spring cache注解进行开发"></a>但是在真正的项目中，使用redis整合spring cache注解会更加方便，开始讲解reids配合spring cache注解进行开发</h3><p>配置还是之前的配置，首先要修改一下RedisConfig配置类，首先添加redis key生成策略</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*生成key的策略 类名+方法名+所有参数值生成唯一的key*/</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> KeyGenerator <span class="title">keyGenerator</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span>  <span class="keyword">new</span> KeyGenerator() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Object <span class="title">generate</span><span class="params">(Object o, Method method, Object... objects)</span> </span>&#123;</span><br><span class="line">            StringBuilder stringBuilder = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">            stringBuilder.append(o.getClass().getName());</span><br><span class="line">            stringBuilder.append(method.getName());</span><br><span class="line">            <span class="keyword">for</span>(Object obj: objects)&#123;</span><br><span class="line">                stringBuilder.append(obj.toString());</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> stringBuilder.toString();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后配置缓存管理器</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> CacheManager <span class="title">cacheManager</span><span class="params">(RedisConnectionFactory redisConnectionFactory)</span></span>&#123;</span><br><span class="line">    <span class="comment">/*生成一个默认配置*/</span></span><br><span class="line">    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();</span><br><span class="line">    <span class="comment">/*设置缓存的默认过期时间且不缓存空值*/</span></span><br><span class="line">    config = config.entryTtl(Duration.ofMinutes(<span class="number">1</span>)).disableCachingNullValues();</span><br><span class="line"></span><br><span class="line">    <span class="comment">/*设置一个初始化的缓存空间set集合*/</span></span><br><span class="line">    Set&lt;String&gt; cacheNames = <span class="keyword">new</span> HashSet&lt;&gt;();</span><br><span class="line">    cacheNames.add(<span class="string">"redis-cache1"</span>);</span><br><span class="line">    cacheNames.add(<span class="string">"redis-cache2"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">/*对每个缓存空间应用不同配置*/</span></span><br><span class="line">    Map&lt;String, RedisCacheConfiguration&gt; configMap = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">    configMap.put(<span class="string">"redis-cache1"</span>, config);</span><br><span class="line">    configMap.put(<span class="string">"redis-cache2"</span>,config.entryTtl(Duration.ofSeconds(<span class="number">120</span>)));</span><br><span class="line"></span><br><span class="line">    RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)</span><br><span class="line">            .initialCacheNames(cacheNames)</span><br><span class="line">            .withInitialCacheConfigurations(configMap)</span><br><span class="line">            .build();</span><br><span class="line">    <span class="keyword">return</span> cacheManager;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>整个配置类代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.ecin520.esp.config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.annotation.JsonAutoDetect;</span><br><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.annotation.PropertyAccessor;</span><br><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.databind.ObjectMapper;</span><br><span class="line"><span class="keyword">import</span> org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.cache.CacheManager;</span><br><span class="line"><span class="keyword">import</span> org.springframework.cache.annotation.CachingConfigurerSupport;</span><br><span class="line"><span class="keyword">import</span> org.springframework.cache.annotation.EnableCaching;</span><br><span class="line"><span class="keyword">import</span> org.springframework.cache.interceptor.KeyGenerator;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.cache.RedisCacheConfiguration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.cache.RedisCacheManager;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.connection.RedisConnectionFactory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.core.RedisTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.core.StringRedisTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Method;</span><br><span class="line"><span class="keyword">import</span> java.time.Duration;</span><br><span class="line"><span class="keyword">import</span> java.util.HashMap;</span><br><span class="line"><span class="keyword">import</span> java.util.HashSet;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"><span class="keyword">import</span> java.util.Set;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*redis配置类*/</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableCaching</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RedisConfig</span> <span class="keyword">extends</span> <span class="title">CachingConfigurerSupport</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/*生成key的策略 类名+方法名+所有参数值生成唯一的key*/</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> KeyGenerator <span class="title">keyGenerator</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span>  <span class="keyword">new</span> KeyGenerator() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> Object <span class="title">generate</span><span class="params">(Object o, Method method, Object... objects)</span> </span>&#123;</span><br><span class="line">                StringBuilder stringBuilder = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">                stringBuilder.append(o.getClass().getName());</span><br><span class="line">                stringBuilder.append(method.getName());</span><br><span class="line">                <span class="keyword">for</span>(Object obj: objects)&#123;</span><br><span class="line">                    stringBuilder.append(obj.toString());</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">return</span> stringBuilder.toString();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="meta">@ConditionalOnMissingBean</span>(name = <span class="string">"redisTemplate"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> RedisTemplate&lt;Object, Object&gt; <span class="title">redisTemplate</span><span class="params">(RedisConnectionFactory redisConnectionFactory)</span></span>&#123;</span><br><span class="line">        <span class="comment">/*序列化，在实体类中需要实现Serializable接口*/</span></span><br><span class="line">        Jackson2JsonRedisSerializer&lt;Object&gt; jackson2JsonRedisSerializer =</span><br><span class="line">                <span class="keyword">new</span> Jackson2JsonRedisSerializer&lt;Object&gt;(Object.class);</span><br><span class="line">        ObjectMapper objectMapper = <span class="keyword">new</span> ObjectMapper();</span><br><span class="line">        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);</span><br><span class="line">        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);</span><br><span class="line">        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);</span><br><span class="line"></span><br><span class="line">        RedisTemplate&lt;Object, Object&gt; template = <span class="keyword">new</span> RedisTemplate&lt;Object, Object&gt;();</span><br><span class="line">        template.setConnectionFactory(redisConnectionFactory);</span><br><span class="line">        template.setKeySerializer(jackson2JsonRedisSerializer);</span><br><span class="line">        template.setValueSerializer(jackson2JsonRedisSerializer);</span><br><span class="line">        template.setHashKeySerializer(jackson2JsonRedisSerializer);</span><br><span class="line">        template.setHashValueSerializer(jackson2JsonRedisSerializer);</span><br><span class="line">        template.afterPropertiesSet();</span><br><span class="line">        <span class="keyword">return</span> template;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="meta">@ConditionalOnMissingBean</span>(StringRedisTemplate.class)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> StringRedisTemplate <span class="title">stringRedisTemplate</span><span class="params">(RedisConnectionFactory redisConnectionFactory)</span></span>&#123;</span><br><span class="line">        StringRedisTemplate template = <span class="keyword">new</span> StringRedisTemplate();</span><br><span class="line">        template.setConnectionFactory(redisConnectionFactory);</span><br><span class="line">        <span class="keyword">return</span> template;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> CacheManager <span class="title">cacheManager</span><span class="params">(RedisConnectionFactory redisConnectionFactory)</span></span>&#123;</span><br><span class="line">        <span class="comment">/*生成一个默认配置*/</span></span><br><span class="line">        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();</span><br><span class="line">        <span class="comment">/*设置缓存的默认过期时间且不缓存空值*/</span></span><br><span class="line">        config = config.entryTtl(Duration.ofMinutes(<span class="number">1</span>)).disableCachingNullValues();</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*设置一个初始化的缓存空间set集合*/</span></span><br><span class="line">        Set&lt;String&gt; cacheNames = <span class="keyword">new</span> HashSet&lt;&gt;();</span><br><span class="line">        cacheNames.add(<span class="string">"redis-cache1"</span>);</span><br><span class="line">        cacheNames.add(<span class="string">"redis-cache2"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*对每个缓存空间应用不同配置*/</span></span><br><span class="line">        Map&lt;String, RedisCacheConfiguration&gt; configMap = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">        configMap.put(<span class="string">"redis-cache1"</span>, config);</span><br><span class="line">        configMap.put(<span class="string">"redis-cache2"</span>,config.entryTtl(Duration.ofSeconds(<span class="number">120</span>)));</span><br><span class="line"></span><br><span class="line">        RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)</span><br><span class="line">                .initialCacheNames(cacheNames)</span><br><span class="line">                .withInitialCacheConfigurations(configMap)</span><br><span class="line">                .build();</span><br><span class="line">        <span class="keyword">return</span> cacheManager;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="有一个地方要注意，如果项目使用了shiro，注解将失效，必须在Relm中加入-Lazy注解"><a href="#有一个地方要注意，如果项目使用了shiro，注解将失效，必须在Relm中加入-Lazy注解" class="headerlink" title="有一个地方要注意，如果项目使用了shiro，注解将失效，必须在Relm中加入@Lazy注解"></a>有一个地方要注意，如果项目使用了shiro，注解将失效，必须在Relm中加入@Lazy注解</h3><p><img src="http://106.15.200.82/source/1572835256334.jpg" alt="image.png"></p>
<p>创建一个实体类，必须要实现序列化接口Serializable</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.ecin520.esp.entity;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.Serializable;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> <span class="keyword">implements</span> <span class="title">Serializable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Integer id;</span><br><span class="line">    <span class="keyword">private</span> String username;</span><br><span class="line">    <span class="keyword">private</span> String password;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">getId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setId</span><span class="params">(Integer id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.id = id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getUsername</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> username;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setUsername</span><span class="params">(String username)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.username = username;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getPassword</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> password;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setPassword</span><span class="params">(String password)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.password = password;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"User&#123;"</span> +</span><br><span class="line">                <span class="string">"id='"</span> + id + <span class="string">'\''</span> +</span><br><span class="line">                <span class="string">", username='"</span> + username + <span class="string">'\''</span> +</span><br><span class="line">                <span class="string">", password='"</span> + password + <span class="string">'\''</span> +</span><br><span class="line">                <span class="string">'&#125;'</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>写两个数据库操作</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Insert</span>(<span class="string">"INSERT `user`(`id`,`username`,`password`) VALUES(#&#123;id&#125;,#&#123;username&#125;,#&#123;password&#125;)"</span>)</span><br><span class="line"><span class="function">Boolean <span class="title">insertUser</span><span class="params">(Integer id, String username, String password)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Select</span>(<span class="string">"SELECT * FROM user where id=#&#123;id&#125;"</span>)</span><br><span class="line"><span class="function">User <span class="title">getUser</span><span class="params">(Integer id)</span></span>;</span><br></pre></td></tr></table></figure>
<p>一般在业务层写缓存<br>向数据库添加用户且存入缓存</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="meta">@CachePut</span>(cacheNames = <span class="string">"user"</span>,key = <span class="string">"#id"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> Boolean <span class="title">insertUser</span><span class="params">(Integer id, String username, String password)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">        userDao.insertUser(id,username,password);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;<span class="keyword">catch</span> (Exception e)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>查询操作，如果缓存没有数据，则首先数据库查询然后存入缓存，下一次则直接从缓存读取数据</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="meta">@Cacheable</span>(cacheNames = <span class="string">"user"</span>,key = <span class="string">"#id"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">getUserById</span><span class="params">(Integer id)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> userDao.getUser(id);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们来讲解一下Cache的一些注解</p>
<h4 id="Cacheable"><a href="#Cacheable" class="headerlink" title="@Cacheable"></a>@Cacheable</h4><p>配置在方法或类上，作用：本方法执行后，先去缓存看有没有数据，如果没有，从数据库中查找出来，给缓存中存一份，返回结果，下次本方法执行，在缓存未过期情况下，先在缓存中查找，有的话直接返回，没有的话从数据库查找，主要针对方法的注解，可以根据方法请求参数对返回值进行缓存。主要参数有</p>
<ul>
<li>value （缓存的名称，必须指定至少一个,@Cacheable(value = “user”)或者@Cacheable(value = {“user”,”role”})）</li>
<li>key （可选，缓存的key，如果需要指定参数则需要使用SPEL表达式编写，否则默认使用方法所有参数组合，@Cacheable(value = “user”, key=”#username”)）</li>
<li>condition unless （缓存的条件，可以为空）</li>
<li><h4 id="CachePut"><a href="#CachePut" class="headerlink" title="@CachePut"></a>@CachePut</h4>也是针对方法使用，可以根据方法请求参数对返回值进行缓存，和@Cacheable不同的是每次都会触发真实的查询。类似于更新操作，即每次不管缓存中有没有结果，都从数据库查找结果，并将结果更新到缓存，并返回结果。</li>
<li>参数和@Cacheable一样</li>
<li><h4 id="CacheEvict"><a href="#CacheEvict" class="headerlink" title="@CacheEvict"></a>@CacheEvict</h4>用来清除用在本方法或者类上的缓存数据，针对方法配置，根据一定的条件对缓存进行清空</li>
<li>value key condition等@Cacheable一样</li>
<li>allEntries 是否清空所有缓存内容，默认false</li>
</ul>

  </div>
</article>



        
          <div id="footer-post-container">
  <div id="footer-post">

    <div id="nav-footer" style="display: none">
      <ul>
         
          <li><a href="/">Home</a></li>
         
          <li><a href="/about/">About</a></li>
         
          <li><a href="/archives/">Writing</a></li>
         
          <li><a href="/projects_url">Projects</a></li>
        
      </ul>
    </div>

    <div id="toc-footer" style="display: none">
      <ol class="toc"><li class="toc-item toc-level-4"><a class="toc-link" href="#pom-xml添加依赖"><span class="toc-number">1.</span> <span class="toc-text">pom.xml添加依赖</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#开启缓存注解"><span class="toc-number">2.</span> <span class="toc-text">开启缓存注解</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#添加配置类RedisConfig"><span class="toc-number">3.</span> <span class="toc-text">添加配置类RedisConfig</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#application-yml"><span class="toc-number">4.</span> <span class="toc-text">application.yml</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#使用时需要注入"><span class="toc-number">5.</span> <span class="toc-text">使用时需要注入</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#simple-sample"><span class="toc-number"></span> <span class="toc-text">simple sample</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#缓存普通k-v"><span class="toc-number">0.1.</span> <span class="toc-text">缓存普通k-v</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#设置过期时间"><span class="toc-number">0.2.</span> <span class="toc-text">设置过期时间</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#对象缓存"><span class="toc-number">0.3.</span> <span class="toc-text">对象缓存</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#读取"><span class="toc-number">0.4.</span> <span class="toc-text">读取</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#存取List"><span class="toc-number">0.5.</span> <span class="toc-text">存取List</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#但是在真正的项目中，使用redis整合spring-cache注解会更加方便，开始讲解reids配合spring-cache注解进行开发"><span class="toc-number"></span> <span class="toc-text">但是在真正的项目中，使用redis整合spring cache注解会更加方便，开始讲解reids配合spring cache注解进行开发</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#有一个地方要注意，如果项目使用了shiro，注解将失效，必须在Relm中加入-Lazy注解"><span class="toc-number"></span> <span class="toc-text">有一个地方要注意，如果项目使用了shiro，注解将失效，必须在Relm中加入@Lazy注解</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Cacheable"><span class="toc-number">1.</span> <span class="toc-text">@Cacheable</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#CachePut"><span class="toc-number">2.</span> <span class="toc-text">@CachePut</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#CacheEvict"><span class="toc-number">3.</span> <span class="toc-text">@CacheEvict</span></a></li></ol>
    </div>

    <div id="share-footer" style="display: none">
      <ul>
  <li><a class="icon" href="http://www.facebook.com/sharer.php?u=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/" target="_blank" rel="noopener"><i class="fab fa-facebook fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://twitter.com/share?url=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&text=Springboot整合redis" target="_blank" rel="noopener"><i class="fab fa-twitter fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.linkedin.com/shareArticle?url=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&title=Springboot整合redis" target="_blank" rel="noopener"><i class="fab fa-linkedin fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://pinterest.com/pin/create/bookmarklet/?url=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&is_video=false&description=Springboot整合redis" target="_blank" rel="noopener"><i class="fab fa-pinterest fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=Springboot整合redis&body=Check out this article: http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/" target="_blank" rel="noopener"><i class="fas fa-envelope fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://getpocket.com/save?url=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&title=Springboot整合redis" target="_blank" rel="noopener"><i class="fab fa-get-pocket fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://reddit.com/submit?url=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&title=Springboot整合redis" target="_blank" rel="noopener"><i class="fab fa-reddit fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.stumbleupon.com/submit?url=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&title=Springboot整合redis" target="_blank" rel="noopener"><i class="fab fa-stumbleupon fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://digg.com/submit?url=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&title=Springboot整合redis" target="_blank" rel="noopener"><i class="fab fa-digg fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.tumblr.com/share/link?url=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&name=Springboot整合redis&description=" target="_blank" rel="noopener"><i class="fab fa-tumblr fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://news.ycombinator.com/submitlink?u=http://yoursite.com/2019/10/17/Springboot%E6%95%B4%E5%90%88redis/&t=Springboot整合redis" target="_blank" rel="noopener"><i class="fab fa-hacker-news fa-lg" aria-hidden="true"></i></a></li>
</ul>

    </div>

    <div id="actions-footer">
        <a id="menu" class="icon" href="#" onclick="$('#nav-footer').toggle();return false;"><i class="fas fa-bars fa-lg" aria-hidden="true"></i> Menu</a>
        <a id="toc" class="icon" href="#" onclick="$('#toc-footer').toggle();return false;"><i class="fas fa-list fa-lg" aria-hidden="true"></i> TOC</a>
        <a id="share" class="icon" href="#" onclick="$('#share-footer').toggle();return false;"><i class="fas fa-share-alt fa-lg" aria-hidden="true"></i> Share</a>
        <a id="top" style="display:none" class="icon" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up fa-lg" aria-hidden="true"></i> Top</a>
    </div>

  </div>
</div>

        
        <footer id="footer">
  <div class="footer-left">
    Copyright &copy; 2020 ECIN520
  </div>
  <div class="footer-right">
    <nav>
      <ul>
         
          <li><a href="/">Home</a></li>
         
          <li><a href="/about/">About</a></li>
         
          <li><a href="/archives/">Writing</a></li>
         
          <li><a href="/projects_url">Projects</a></li>
        
      </ul>
    </nav>
  </div>
</footer>

    </div>
    <!-- styles -->
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
<link rel="stylesheet" href="/lib/justified-gallery/css/justifiedGallery.min.css">

    <!-- jquery -->
<script src="/lib/jquery/jquery.min.js"></script>
<script src="/lib/justified-gallery/js/jquery.justifiedGallery.min.js"></script>
<!-- clipboard -->

  <script src="/lib/clipboard/clipboard.min.js"></script>
  <script type="text/javascript">
  $(function() {
    // copy-btn HTML
    var btn = "<span class=\"btn-copy tooltipped tooltipped-sw\" aria-label=\"Copy to clipboard!\">";
    btn += '<i class="far fa-clone"></i>';
    btn += '</span>'; 
    // mount it!
    $(".highlight table").before(btn);
    var clip = new ClipboardJS('.btn-copy', {
      text: function(trigger) {
        return Array.from(trigger.nextElementSibling.querySelectorAll('.code')).reduce((str,it)=>str+it.innerText+'\n','')
      }
    });
    clip.on('success', function(e) {
      e.trigger.setAttribute('aria-label', "Copied!");
      e.clearSelection();
    })
  })
  </script>

<script src="/js/main.js"></script>
<!-- search -->

<!-- Google Analytics -->

<!-- Baidu Analytics -->

<!-- Disqus Comments -->


</body>
</html>
